﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using PanasonicWarranty.Business;
using System.Web.UI.HtmlControls;
using Utils;
using System.IO;
using Settings;
using System.Data;
namespace PanasonicWarranty.UI
{
    public partial class ModelManagement : BasePageManageWarranty
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        void paging_PagingChange(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            pagingbottom.CurrentPage = (sender as UserControl.ucPaging).CurrentPage;
            BindGridData();
            pagingtop.Visible = pagingbottom.Visible = (sender as UserControl.ucPaging).TotalPage > 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                pagingtop.PageDisplay = pagingbottom.PageDisplay = 6;
                BindDropDownData();
                BindGridData();
            }
        }


        private void BindGridData()
        {
            try
            {
                string modelcode = txtSearchModelCode.Text.Trim();
                string catecode = txtSearchCateCode.Text.Trim();
                int? period = txtSearchPeriod.Text.Trim() == string.Empty ?
                                (int?)null : Convert.ToInt32(txtSearchPeriod.Text.Trim());
                string periodtype = ddlSearchPeriodType.SelectedValue;
                bool? happycall = ddlSearchHappyCall.SelectedValue == string.Empty ?
                                (bool?)null : Convert.ToBoolean(ddlSearchHappyCall.SelectedValue);
                int currentPage = pagingtop.CurrentPage;
                int pageSize = pagingtop.PageSize;
                int totalRow = 0;
                grvData.DataSource = pa_Model.Paging(currentPage, pageSize, ref totalRow, modelcode, catecode, period, periodtype, happycall);
                pagingtop.TotalRecord = pagingbottom.TotalRecord = totalRow;
                pagingtop.Visible = pagingbottom.Visible = pagingtop.TotalPage > 1;
                grvData.DataBind();
                ltrInfo.Text = "Tổng cộng: " + totalRow;
            }
            catch { }
        }

        private void BindDropDownData()
        {
            ddlCateCode.DataSource = DB.pa_Categories.ToList();
            ddlCateCode.DataValueField = "CateCode";
            ddlCateCode.DataTextField = "CateCode";
            ddlCateCode.DataBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            pagingtop.PagingChange -= new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange -= new EventHandler(paging_PagingChange);
            pagingtop.CurrentPage = pagingbottom.CurrentPage = 1;
            pagingtop.PagingChange += new EventHandler(paging_PagingChange);
            pagingbottom.PagingChange += new EventHandler(paging_PagingChange);
            BindGridData();
        }

        protected void tSortable_length_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                PageSize = Convert.ToInt32(tSortable_length.SelectedValue);
                pagingtop.PageSize = pagingbottom.PageSize = PageSize;
                BindGridData();
            }
            catch { }
        }

        protected void grvData_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                string modelCode = (string)e.CommandArgument;
                hdfID.Value = modelCode;
                switch (e.CommandName)
                {
                    case "Editing":
                        var obj = DB.pa_Models.FirstOrDefault(p => p.ModelCode == modelCode);
                        if (obj != null)
                        {
                            txtModelCode.Enabled = false;
                            txtModelCode.Text = obj.ModelCode;
                            ddlCateCode.SelectedValue = obj.CateCode;
                            txtPeriod.Text = obj.WarrantyPeriod.ToString();
                            ddlPeriodType.SelectedValue = obj.PeriodType;
                            txtDescription.Text = obj.Description;
                            chkHappyCall.Checked = obj.ApprovedRequired ?? false;
                            txtApprovedDuration.Text = (obj.ApprovedDuration ?? 0).ToString();
                            RegisterStartUpScript("OpenDialog('dialog1',400);");
                        }
                        break;
                    case "Deleting":
                        Authorize(Role.Write);
                        obj = DB.pa_Models.FirstOrDefault(p => p.ModelCode == modelCode);
                        if (obj != null)
                        {
                            DB.pa_Models.DeleteOnSubmit(obj);
                            DB.SubmitChanges();
                            BindGridData();
                            InsertChangeLog("Xóa dữ liệu model sản phẩm");
                        }
                        break;
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Write);
                if (ValidateInfo())
                {
                    pa_Model obj;
                    if (hdfID.Value == "")//Add new
                    {
                        obj = new pa_Model();
                        obj.ModelCode = txtModelCode.Text.Trim();
                    }
                    else //Edit
                    {
                        obj = DB.pa_Models.FirstOrDefault(p => p.ModelCode == hdfID.Value);
                    }
                    obj.CateCode = ddlCateCode.SelectedValue;
                    obj.Disabled = false;
                    obj.WarrantyPeriod = int.Parse(txtPeriod.Text.Trim());
                    obj.PeriodType = ddlPeriodType.SelectedValue;
                    obj.Description = txtDescription.Text;
                    obj.ApprovedRequired = chkHappyCall.Checked;
                    obj.ApprovedDuration = txtApprovedDuration.Text.ToInt();
                    //Save
                    if (hdfID.Value == "")
                        DB.pa_Models.InsertOnSubmit(obj);
                    DB.SubmitChanges();
                    BindGridData();
                    InsertChangeLog(hdfID.Value == "" ? "Thêm mới dữ liệu model sản phẩm" : "Cập nhật dữ liệu model sản phẩm");
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void lbtnAddNew_Click(object sender, EventArgs e)
        {
            ControlClass.ResetControlValues(pnl_dialog1);
            txtModelCode.Enabled = true;
            RegisterStartUpScript("OpenDialog('dialog1',400);");
        }

        protected override bool ValidateInfo()
        {
            string errMsg = string.Empty;
            if (string.IsNullOrWhiteSpace(txtModelCode.Text))
                errMsg = "Bắt buộc nhập model";
            else if (string.IsNullOrWhiteSpace(txtPeriod.Text))
                errMsg = "Bắt buộc nhập thời hạn bảo hành";
            if (errMsg != string.Empty)
            {
                lbError.Text = errMsg;
                RegisterStartUpScript("OpenDialog('dialog1',400);");
                return false;
            }
            else
            {
                lbError.Text = string.Empty;
                return true;
            }
        }

        protected void btnDownload_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Download);
                DownloadFile_Tracking(Server.MapPath(string.Format(@"~/App_Data/{0}", AppSetting.PatternFileUploadModel)));
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                Authorize(Role.Export);
                using (DataTable dt = pa_Model.GetAll())
                {
                    if (dt.Rows.Count > 0)
                    {
                        //Transform table
                        foreach (DataColumn col in dt.Columns)
                        {
                            col.Caption = pa_Model.GetCaption(col.ColumnName);
                        }
                        ExportToExcel(dt, "ExportModel.xlsx");
                    }
                    else
                    {
                        ShowMessageBox("Không có dữ liệu export");
                    }
                }
                InsertChangeLog("Export dữ liệu model sản phẩm");
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            BindGridData();
        }

        [WebMethod]
        public static void SetApprovedRequired(bool required, string modelCode)
        {
            if (SAuthorize(Role.Write))
            {
                pa_Model.SetApprovedRequired(required, modelCode);
                SInsertChangeLog("Cập nhật dữ liệu model sản phẩm");
            }
            else
                throw new CustomException("Bạn không có quyền thực hiện chức năng này");
        }
    }
}